package com.kobeliu.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class WSServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline.addLast(new HttpServerCodec());
        //对大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //netty 编程中都要用
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        //============ 以上用于支持http协议 ===============================

        //============ 增加心跳机制的支持 ===============================
        pipeline.addLast(new IdleStateHandler(8,
                10,
                600));
        pipeline.addLast(new HeartBeatHandler());




        //============ 以下用于支持websocket协议==========================
        /**
         * websocket服务器处理的协议 用于指定给客户端连接访问的路由 /ws
         * 此handler会处理一些繁重的任务
         * 握手 close ping+pong 心跳机制
         * 对于webSocket来讲 都是以frames来进行传输 不同数据类型对应的frames也不同
         */
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        //自定义处理器
        pipeline.addLast(new ChatHandler());


    }
}
